var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var http = require('http');
var helmet = require('helmet');
var fs = require('fs');

var index = require('./server/routes/index');
var users = require('./server/routes/users');


// import api
var manhua = require('./server/api/manhua');
var user = require('./server/api/user');
var favors = require('./server/api/favors');
var historys = require('./server/api/historys');

var tokenDao = require('./server/api/tokenDao');


var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(cookieParser());

// 加防护
app.use(helmet());

// 加token验证检测机制
app.use('/api/user', expressJwt({
    secret: tokenDao.secret,
    getToken: function fromHeaderOrQuerystring(req, res) {

        if (req.get('token')) {

            return req.get('token');

        } else if (req.query && req.query.token) {

            return req.query.token;
        } else {
            console.log('not find token');

            return null;
        }


    },
    isRevoked: tokenDao.isRevoked
}).unless({ path: ['/api/user/sign', '/api/user/login'] }));



// create a write stream (in append mode)  log 错误日志
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'error.log'), { flags: 'a' });
app.use(logger('combined', {
    skip: function (req, res) { return res.statusCode < 400 },
    stream: accessLogStream
}));

// static
app.use('/client', express.static(path.join(__dirname, 'client')));
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/assets', express.static(path.join(__dirname, 'public/assets')));
// app.use('/api', api);
app.use('/api/manhua', manhua);
app.use('/api/user', user);
app.use('/api/favors', favors);
app.use('/api/historys', historys);

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    console.log('-------error handel--------');
    console.log(err);

    // token的错误集中处理·
    if (err.name === 'UnauthorizedError') {

        console.log(req.url);

        if (req.url === '/api/user/favor' || req.url === '/api/user/verify') {
            return res.status(200).send({
                success: false,
                token_message: 'No token provided.'
            });
        } else {
            return res.status(200).send({
                success: false,
                message: 'No token provided.'
            });
        }


    }

    // render the error page
    res.status(err.status || 500);
    res.send(err);
});

//设置跨域访问
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*'); //允许所有域
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); //您可以发送  POST和GET请求此服务。
    //X-Requested-With 并content-type 允许头文件。
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    res.header("Content-Type", "application/json;charset=utf-8");

    next();
});




http.createServer(app).listen(3000, function () {
    console.log('listen on port 3000');
});